package com.wzk.travelspringboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wzk.travelspringboot.common.LogToFile;
import com.wzk.travelspringboot.common.RedisConstant;
import com.wzk.travelspringboot.dao.ScenicTypeDAO;
import com.wzk.travelspringboot.dto.Result;
import com.wzk.travelspringboot.entity.ScenicType;
import com.wzk.travelspringboot.service.ScenicTypeService;
import com.wzk.travelspringboot.vo.ScenicTypeVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * @Author: WangZiKang
 * @Date: 2025/1/6 22:02
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ScenicTypeServiceImpl extends ServiceImpl<ScenicTypeDAO, ScenicType> implements ScenicTypeService {

    private final StringRedisTemplate stringRedisTemplate;

    private final ObjectMapper objectMapper;

    public static final Logger logger = Logger.getLogger(ScenicTypeServiceImpl.class.getName());

    @Override
    public Result getAllType() {
        try {
            //1.判断缓存中是否存在
            String typeJson = stringRedisTemplate.opsForValue().get(RedisConstant.SCENIC_TYPE_KEY);
            if (StrUtil.isNotBlank(typeJson)){
                List<ScenicTypeVO> cachedVos = objectMapper.readValue(typeJson, new TypeReference<List<ScenicTypeVO>>() {});
                return Result.success(cachedVos);
            }
            List<ScenicType> list = query().list();
            if (list.isEmpty()){
                return Result.success(Collections.emptyList());
            }
            List<ScenicTypeVO> vos = list.stream().map(st -> BeanUtil.copyProperties(st, ScenicTypeVO.class)).collect(Collectors.toList());
            String json = objectMapper.writeValueAsString(vos);
            //存到redis
            stringRedisTemplate.opsForValue().set(RedisConstant.SCENIC_TYPE_KEY,json,RedisConstant.SCENIC_TYPE_TIME, TimeUnit.MINUTES);
            return Result.success(vos);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            log.error("ScenicTypeImpl.getAllType json转换出现异常!异常：{}",e.getMessage());
            LogToFile.logToFile("ScenicTypeImpl.getAllType json转换出现异常!异常："+e.getMessage(),logger,"json_convert_err");
            return Result.failed("类别加载出现异常！请联系管理员");
        }
    }

    @Override
    public Result insertType(String typeName) {
        //1.判断长度是否正确
        if (typeName.length() < 2){
            return Result.failed("数据不合法！");
        }
        ScenicType scenicType = new ScenicType();
        scenicType.setTypeName(typeName);
        scenicType.setCreateTime(LocalDateTime.now());
        scenicType.setUpdateTime(LocalDateTime.now());
        boolean b = save(scenicType);
        if (!b){
            log.error("ScenicType数据插入失败:{}",scenicType);
            LogToFile.logToFile("ScenicType插入失败！数据:"+scenicType,logger,"type_add_err");
            return Result.failed("添加类别失败！出现未知问题请联系管理员");
        }
        //2.删除缓存数据
        stringRedisTemplate.delete(RedisConstant.SCENIC_TYPE_KEY);
        return Result.success("添加成功!",null);
    }
}
